﻿using System;
using System.Web;
using System.Web.Security;
using CIK.News.Framework;

namespace CIK.News.Web.Infrastructure.Security
{
    public class FormsAuthenticationService : IFormsAuthenticationService
    {
        public void SignIn(UserInfo userInfo, bool createPersistentCookie)
        {
            Guard.ArgumentNotNullOrEmpty(userInfo.UserName, "UserName");

            //FormsAuthentication.SetAuthCookie(userName, createPersistentCookie);

            //TODO: get the time from web Config
            const int timeout = 60 * 8;

            var expirationTime = DateTime.Now.AddMinutes(timeout);
            if (createPersistentCookie)
            {
                expirationTime = DateTime.Now.AddDays(2);
            }

            var userData = new UserData()
            {
                DisplayName = userInfo.DisplayName,
                Token = userInfo.Token
            };

            var ticket = new FormsAuthenticationTicket(1,
                                                       userInfo.UserName, DateTime.Now,
                                                       expirationTime,
                                                       createPersistentCookie, userData.ToString(),
                                                       FormsAuthentication.FormsCookiePath);

            // Encrypt the ticket.
            var encryptedTicket = FormsAuthentication.Encrypt(ticket);

            // Create the cookie.
            var cookie = new HttpCookie(FormsAuthentication.FormsCookieName, encryptedTicket);

            // Set the cookie's expiration time to the tickets expiration time         
            if (ticket.IsPersistent)
                cookie.Expires = ticket.Expiration;

            HttpContext.Current.Response.Cookies.Add(cookie);
        }

        public void SignOut()
        {
            FormsAuthentication.SignOut();
        }
    }
}